import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Clipboard,
  Platform,
  TouchableOpacity
} from 'react-native';

import { GiftedChat, Send, Bubble, Composer, Actions, LoadEarlier, InputToolbar, Message } from 'react-native-gifted-chat';
import MessageText from './messageText';
import MessageImage from './messageImage';
import ImagePicker from 'react-native-image-picker';
import Toast from 'react-native-sk-toast';
import api from '../../services/api';
import _ from 'lodash';
import Communications from 'react-native-communications';

import moment from 'moment';

class MessageView extends Component {

    constructor(props) {
      super(props);
      this.state = {
          messages: [],
          isLoadingEarlier: false,
          loadEarlier: true,
          page: 1,
          isDisable: false,
      };

      this.onSend = this.onSend.bind(this);
      this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
    }

    async componentWillMount() {
        let {userInfo, actions, dispatch} = this.props;
        // await this._createSession();
        dispatch(actions.global.global_is_enter_message(true));
        //删除缓存
        await api.post('/housekeeper/delmessagebyid',{id: userInfo.id});
        // await this._getMessageList();

    }

    async _onNavigatorEvent(event){
        if (event.type == 'NavBarButtonPress') {
          let {session} = this.props;
          let title = session && session.user && session.user.productKey == "HuLiZhan" ? "新增护理服务":"新增任务"
              if (event.id == 'add') {
                  if(this.state.isDisable){
                      return;
                  }

                  await this.setState({isDisable:true});//防重复点击

                  let {userInfo} = this.props;
                  this.props.navigator.push({
                           title: title,
                           screen: 'housekeeperapp.addorder',
                           backButtonTitle:'',
                            passProps: {
                                source: 'create',
                                userPhone: userInfo.phone,
                            },
                            navigatorStyle:{
                              tabBarHidden: true,
                              navBarTextColor: 'white',
                              navBarButtonColor: 'white',
                              navBarBackgroundColor: '#EA5404',
                              statusBarColor: '#EA5404',
                              navBarTitleTextCentered: true,
                              topBarElevationShadowEnabled:false
                          },
                          navigatorButtons: {
                            rightButtons: [
                                {
                                    id: 'clear',
                                    testID: 'order_clear',
                                    title: '清空'
                                }
                            ]
                        }
                    });

                    this.timer = setTimeout(async()=>{
                        await this.setState({isDisable:false});//1.0秒后可点击
                    },1000);
              }else if(event.id == 'phone'){
                  let {userInfo} = this.props;
                  Communications.phonecall(userInfo.phone, true);
              }
        }
    }

    async _createSession(){

        let {userInfo, session} = this.props;
        let json = JSON.stringify({
                        "kf_account" : session.user.kf_account,
                        "openid" : userInfo.wxOpenId
                    });

        let send_res = await api.post('/wx/createsession',{json});

        console.log("###",  send_res);
    }

    async _getMessageList(){

        let now = new Date();
        let date = new Date(now.getTime() - 1 * 12 * 3600 * 1000);

        let json = JSON.stringify({
                        "starttime": Math.round(date.getTime()/1000),
                        "endtime": Math.round(now.getTime()/1000),
                        "msgid": 1,
                        "number": 1000
                    });
        let {userInfo} = this.props;

        // let json = JSON.stringify({
        //                 "starttime": Math.round(date.getTime()/1000),
        //                 "endtime": Math.round(now.getTime()/1000),
        //                 "openid": userInfo.wxOpenId,
        //                 "pagesize": 50,
        //                 "pageindex": 1
        //             });

        let send_res = await api.post('/wx/getmessagelist',{json});

        console.log("###",  send_res);
    }

    componentWillUnmount(){
        let {actions, dispatch} = this.props;
        // await this._createSession();
        dispatch(actions.global.global_is_enter_message(false));

        this.timer && clearTimeout(this.timer);
    }

    updateView(messages = []){
        //更新界面
        this.setState((previousState) => {
          return {
            messages: GiftedChat.append(previousState.messages, messages),
          };
        });
    }

    async onSend(messages) {
      let {userInfo, session, actions, dispatch} = this.props;

      let other = _.concat(messages, this.props.message[userInfo.id]);

      if(other && other.length > 30){//大于30条时，去掉最久的一半，并向数据库保存下来
          await api.post('/message/storemessage',{user_id:userInfo.id, logjson:JSON.stringify(_.drop(other, 15))});
          other = _.dropRight(other, 15);
      }

      dispatch(actions.message.message_change(userInfo.id, other));

      //真实发消息
      let json = JSON.stringify({
                      "touser": userInfo.wxOpenId,
                      "msgtype":"text",
                      "text":
                      {
                           "content": messages[0].text,
                      },
                      "customservice":
                      {
                          "kf_account": session.user.kf_account
                      }
                  });

      let send_res = await api.post('/wx/customsend',{json});

    }
    _renderSend(sendProps){
        return (
            <Send
                {...sendProps}
                label={'发送'}
                textStyle={{color: "#EA5404", fontWeight:'normal', marginBottom: Platform.OS=='ios'?16:11}}
            />
        );
    }

    _renderBubble(bubbleProps){
        return (
            <Bubble
                {...bubbleProps}
                onLongPress={(context)=>{
                    const options = [
                      '复制',
                      '取消',
                    ];
                    const cancelButtonIndex = options.length - 1;
                    context.actionSheet().showActionSheetWithOptions({
                      options,
                      cancelButtonIndex,
                      tintColor: "#EA5404",
                    },
                    (buttonIndex) => {
                      switch (buttonIndex) {
                        case 0:
                          Clipboard.setString(bubbleProps.currentMessage.text);
                          break;
                      }
                    });
                }}
                containerStyle={{
                    left:{
                        marginBottom: 5,
                    },
                    right:{
                        marginBottom: 5,
                    }
                }}
                wrapperStyle={{
                    left:{
                        borderRadius:4,
                        backgroundColor: "#f0f0f0"
                    },
                    right:{
                        borderRadius:4,
                        backgroundColor: "#EA5404"
                    }
                }}
                containerToNextStyle={{
                    left:{
                      borderBottomLeftRadius: 2,
                    },
                    right:{
                      borderBottomRightRadius: 2,
                    }
                }}
                containerToPreviousStyle={{
                    left:{
                      borderTopLeftRadius: 2,
                    },
                    right:{
                      borderTopRightRadius: 2,
                    }
                }}
            />
        )
    }

    _renderComposer(composerProps){
        return (
            <Composer
                {...composerProps}
                placeholder={"输入消息..."}
                textInputStyle={{fontSize:14,marginTop:Platform.select({
                  ios: 9,
                  android: 0,
                }),}}
            />
        )
    }

    _renderInputToolbar(inputToolbarProps){
        return (
            <InputToolbar
                {...inputToolbarProps}
                primaryStyle={{justifyContent:'center'}}
            />
        )
    }

    _renderMessageText(messageTextProps){
        return (
            <MessageText
                {...messageTextProps}
            />
        )
    }

    _renderMessageImage(messageImageProps){
        return (
            <MessageImage
                {...messageImageProps}
                lightboxProps={{
                    swipeToDismiss:true,
                    renderHeader:(close) =>(
                        <TouchableOpacity onPress={close}>
                          <Text style={{color: 'white',backgroundColor: '#EA5404', overflow:'hidden',padding: 8,borderRadius: 3,textAlign: 'center',margin: 40,alignSelf:'flex-end',}}>关闭</Text>
                        </TouchableOpacity>
                    )
                }}

            />
        )
    }

    _actionImagePicker(type, actionsProps){
        const options = {
            title: '拍照',
            cancelButtonTitle: "取消",
            quality: 0.5,
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };

        if(type == 1){//照相
            ImagePicker.launchCamera(options, (response) => {
                if (response.didCancel) {
                    console.log('User cancelled image picker');
                }
                else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                }
                else {
                    actionsProps.onSend([{image:response.uri}]);
                }

            });
        }else if(type == 2){
            ImagePicker.launchImageLibrary(options, (response) => {
                if (response.didCancel) {
                    console.log('User cancelled image picker');
                }
                else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                }
                else {
                    actionsProps.onSend([{image:response.uri}]);
                }
            });
        }
    }

    _renderActions(actionsProps){
        return (
            <Actions
                {...actionsProps}
                options={{
                    '照相':()=>{
                        this._actionImagePicker(1, actionsProps);
                    },
                    '选择相册':()=>{
                        this._actionImagePicker(2, actionsProps);
                    },
                    '取消':()=>{

                    }
                }}
                optionTintColor={"#EA5404"}
                containerStyle={{
                    marginBottom: 12,
                }}
                wrapperStyle={{
                    borderColor: '#EA5404',
                    borderWidth: 1,
                }}
                iconTextStyle={{
                    color: '#EA5404',
                    lineHeight: 23,
                    fontWeight: 'normal'
                }}
            />
        )
    }

    _renderLoadEarlier(loadEarlierProps){

        return (
            <LoadEarlier
                {...loadEarlierProps}
                label={"点击加载更多"}
            />
        )
    }

    async _onLoadEarlier(){
        let {userInfo, message, actions, dispatch} = this.props;
        this.setState((previousState) => {
          return {
            isLoadingEarlier: true,
          };
        });

        let list = await api.post('/message/list',{user_id:userInfo.id,page:this.state.page, pagesize:1});

        // console.log("#####", list);

        if(list.data.res.length > 0){
            let jsonArr = JSON.parse(list.data.res[0].message_log);

            this.setState((previousState) => {
              jsonArr = _.drop(jsonArr);// 开头有条重复去掉
              let other = _.concat(jsonArr, previousState.messages);

            //   console.log("######@@@@", other);
              return {
                messages: other,
                loadEarlier: true,
                isLoadingEarlier: false,
                page: this.state.page+1
              };
            });

        }else {
            this.setState(() => {
              return {
                loadEarlier: false,
                isLoadingEarlier: false,
              };
            });
        }

    }

    render() {
      let {session, userInfo, message} = this.props;
      if(!session){
          return null;
      }

      let uniqMess = _.uniqBy(message[userInfo.id], '_id');

      return (
        <GiftedChat
          messages={message[userInfo.id]?GiftedChat.append(this.state.messages, uniqMess):GiftedChat.append([],this.state.messages)}
          onSend={this.onSend}
          locale={'zh-cn'}
          loadEarlier={this.state.loadEarlier}
          onLoadEarlier={this._onLoadEarlier.bind(this)}
          isLoadingEarlier={this.state.isLoadingEarlier}
          renderInputToolbar={this._renderInputToolbar.bind(this)}
          renderSend={this._renderSend.bind(this)}
          renderBubble={this._renderBubble.bind(this)}
          renderComposer={this._renderComposer.bind(this)}
          renderMessageText={this._renderMessageText.bind(this)}
          renderMessageImage={this._renderMessageImage.bind(this)}
          renderLoadEarlier={this._renderLoadEarlier.bind(this)}
          user={{
            _id: session.user.id,
            name: session.user.keeper_name
          }}
        />
      );
    }
}

var connectHelper = require('../../services/connectHelper');
MessageView = connectHelper(state => state)(MessageView);

module.exports = MessageView;
